package com.sikaryofficial.information.service.articleview;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.sikaryofficial.common.core.constant.BrandEnum;
import com.sikaryofficial.common.core.constant.CacheBusinessConstants;
import com.sikaryofficial.common.redis.service.RedisService;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import com.sikaryofficial.information.config.HISMKInformationProperties;
import com.sikaryofficial.information.domain.entity.ArticleViews;
import com.sikaryofficial.information.service.IArticleViewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author : qinjinyuan
 * @desc : 文件阅读监听
 * @date : 2023/11/01 17:29
 */
@Component
@Slf4j
@SuppressWarnings(value = "unchecked")
public class ArticleViewListener {
    private static final Long SECURITY_DEFAULT_USER_ID = 0L;
    private static final Integer AUDIT_STATUS_PASS = 2;
    @Autowired
    private IArticleViewsService articleViewsService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private HISMKInformationProperties brandTenantProperties;

    /**
     * 监听 详情查看功能： 增加查阅量数据
     *
     * @param event
     */
    @EventListener
    @Async("asyncTaskExecutor")
    public void processViewsEvent(ArticleViewEvent event) {
        if (Objects.isNull(event.getAuditStatus()) || !AUDIT_STATUS_PASS.equals(event.getAuditStatus())) {
            // 未登录用户，不统计阅读量
            log.info("审核状态不对（AuditStatus: {}），不记录阅读量", event.getAuditStatus());
            return;
        }
        Long userId = SecurityUtils.getUserId();
        if (Objects.isNull(userId) || SECURITY_DEFAULT_USER_ID.equals(userId)) {
            // 未登录用户，不统计阅读量
            log.info("用户未登录（userId: {}），不记录阅读量", userId);
            return;
        }
        String cacheKey = buildKey(event, userId);
        if (Boolean.TRUE.equals(redisService.hasKey(cacheKey))) {
            // key存在，则不进行统计
            return;
        }
        ArticleViews entity = new ArticleViews();
        entity.setArticleViewsId(IdWorker.getId());
        entity.setViewCount(1L);
        entity.setArticleId(event.getArticleId());
        entity.setCreatedBy(userId);
        entity.setTenantId(Objects.isNull(event.getTenantId()) ? BrandEnum.HISMK.getValue() : event.getTenantId());
        articleViewsService.insertViews(entity);
        // 缓存2分钟
        redisService.setCacheObject(cacheKey, true, 2L, TimeUnit.MINUTES);
    }

    private String buildKey(ArticleViewEvent event, Long userId) {
        String brandNo = SecurityUtils.getBrand();
        Integer tenantId = brandTenantProperties.getTenantByBrand(brandNo);
        if (Objects.isNull(tenantId)) {
            log.error("bad brandNo:{}", brandNo);
        }
        return MessageFormat.format(CacheBusinessConstants.ARTICLE_VIEWS_CACHE, String.valueOf(event.getArticleId()), String.valueOf(userId), brandNo);
    }
}
